package com.cug.nageoffer.enterprise.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cug.nageoffer.common.exception.GlobalException;
import com.cug.nageoffer.enterprise.user.mapper.EnterpriseUserMapper;
import com.cug.nageoffer.enterprise.user.service.EnterpriseUserService;
import com.cug.nageoffer.model.dto.LoginDto;
import com.cug.nageoffer.model.dto.RegisterDto;
import com.cug.nageoffer.model.entity.EnterpriseUser;
import com.cug.nageoffer.model.entity.User;
import com.cug.nageoffer.model.vo.*;
import com.cug.nageoffer.util.AuthContextUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class EnterpriseUserServiceImpl implements EnterpriseUserService {

    @Autowired
    private EnterpriseUserMapper enterpriseUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private RBloomFilter<String> userRegisterCachePenetrationBloomFilter;


    /**
     * 企业端用户登录
     * @param loginDto
     */
    @Override
    public LoginVo login(LoginDto loginDto) {

        // 根据用户名查询用户
        EnterpriseUser enterpriseUser = enterpriseUserMapper.selectByUsername(loginDto);

        if(enterpriseUser == null){// 无此用户
            throw new GlobalException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 验证密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(inputPassword.getBytes());

        if(!md5Password.equals(enterpriseUser.getPassword())){
            // 密码错误
            throw new GlobalException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 生成token，保存到redis
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        // 保存用户对象
        redisTemplate.opsForValue().set("user:nageoffer:login:"+token, JSONObject.toJSONString(enterpriseUser));

        // 构建返回对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    /**
     * 企业端用户注册
     * @param registerDto
     */
    @Override
    public void register(RegisterDto registerDto) {
        // 注册验证
        boolean exist = userRegisterCachePenetrationBloomFilter.contains(registerDto.getUsername());
        if(exist){
            log.error("用户名已存在！");
            throw new GlobalException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        LoginDto loginDto = new LoginDto();
        loginDto.setUsername(registerDto.getUsername());

        EnterpriseUser registerUser = new EnterpriseUser();
        BeanUtils.copyProperties(registerDto,registerUser);
        registerUser.setPhoneNumber(registerDto.getPhone());

        // 加密密码
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(registerDto.getPassword().getBytes());
        registerUser.setPassword(md5DigestAsHex);
        // 添加到布隆过滤器
        try{
            enterpriseUserMapper.insert(registerUser);
            userRegisterCachePenetrationBloomFilter.add(registerUser.getUsername());
        }catch (Exception e){
            throw new GlobalException(ResultCodeEnum.REGISTER_ERROR);
        }


    }

    /**
     * 企业端用户更新信息
     * @param enterpriseUser
     */
    @Override
    public void enterpriseUserUpdate(EnterpriseUser enterpriseUser) {
        enterpriseUserMapper.update(enterpriseUser);
    }

    /**
     * 查询用户数据
     * @return
     */

    @Override
    public EnterpriseUserVo getUserInfo() {
        Long id = AuthContextUtil.get().getId();

        EnterpriseUser enterpriseUser = enterpriseUserMapper.selectById(id);
        EnterpriseUserVo enterpriseUserVo = new EnterpriseUserVo();
        BeanUtils.copyProperties(enterpriseUser,enterpriseUserVo);
        return enterpriseUserVo;
    }

    /**
     * 查询简历列表
     * @return
     */

    @Override
    public Result<List<ResumeVo>> getResume() {
        // 在ThreadLocal获取用户id
        Long id = AuthContextUtil.get().getId();

        return enterpriseUserMapper.selectResumeById(id);
    }
}
